/**
 * @file       godemool/cmlprinter.cc
 * @brief      Implements IPrinter interface for XML documents.
 * @author     ben "boin" bonoeil
 * @date       2015-02
 */

/* Copyright (c) 2007-2015, ben "boin" bonoeil

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions
   are met:
   * Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
   * Redistributions in binary form must reproduce the above
   copyright notice, this list of conditions and the following
   disclaimer in the documentation and/or other materials provided
   with the distribution.
   * Neither the name of the ben "boin" bonoeil nor the names of its
   contributors may be used to endorse or promote products derived
   from this software without specific prior written permission.

   NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE
   GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY
   ben "boin" bonoeil ''AS IS'' AND ANY EXPRESS OR IMPLIED
   WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   DISCLAIMED. IN NO EVENT SHALL ben "boin" bonoeil BE LIABLE FOR ANY
   DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
   GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
   WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include "godemool/xmlprinter.h"
#include "godemool/error.h"
#include "godemool/base64.h"
#include <cassert>

using namespace boin;
// using namespace tinyxml2;

XmlPrinter::XmlPrinter(std::ostream & stream)
  : os(stream)
{
}

void XmlPrinter::PrintSpace( int depth )
{
  for( int i=0; i<depth; ++i) {
    XMLPrinter::Print("  ");
  }
}

void XmlPrinter::Open(const std::string & title, const Hl2Demo::Header & header)
{
  const bool writeBOM = false, writeDeclaration = false;
  PushHeader(writeBOM, writeDeclaration);
  PushDeclaration("xml version=\"1.0\" encoding=\"UTF-8\"");

  PushComment(" Generated by " PACKAGE_STRING " ");
  PushComment(" Visit " PACKAGE_URL " ");
  OpenElement("hl2demo",false);
  OpenElement("source",false); {
    PushText(title.c_str()); }
  CloseElement(true);
  IPrinter::Print(header);
}

void XmlPrinter::Flush()
{
  int size = CStrSize();
  if (size > 0) {
    os.write(CStr(), size-1);
    tinyxml2::XMLPrinter::ClearBuffer();
  }
}

void XmlPrinter::Close()
{
  CloseElement(false);
  Flush();
}

XmlPrinter::~XmlPrinter()
{
  Flush();
}

void XmlPrinter::BegElt(const char * name)
{
  OpenElement(name,false);
}

void XmlPrinter::EndElt(const char * name)
{
  CloseElement(false);
  Flush();
}

void XmlPrinter::Attr(const char * name, const char * val)
{
  PushAttribute(name,val);
}

void XmlPrinter::Str(const char * data)
{
  if (*data) // Prevent discarding element compact format for nothing
    PushText(data);
}

void XmlPrinter::Data(const WalkData & data)
{
  int len = data.Size();
  if (!len) return;
  const char * type = "raw";
  int it = 0;

  // Scan data to determine how to encode it.
  for (int i = 0; i != len ; ) {
    const int c = data.At(i++);
    if (c <= 0x20 || c >= 128) {
      /* Not a graphic char */
      if (!c && len > 1 && ++i == len) {
        // C-string must be non-empty and 0 terminated
        type = "str";
      } else if (len <= 16) {
        // Small data, using hexa style
        type = nullptr;
        char str[16*2+1];
        int j = 0;
        do {
          static const char hex[] = "0123456789ABCDEF";
          int c = 255 & data.At(it++);
          str[j++] = hex[c>>4];
          str[j++] = hex[c&15];
          //str[j++] = '-';
        } while (it != len);
        str[j] = 0;
        BegElt("hex"); Str(str); EndElt("hex");
      } else {
        // Have some non-graphic chars : base64
        type = nullptr;
        const int max = 14*3;
        base64::string b64(max);
        do {
          int cnt = len > max ? max : len;
          len -= cnt;
          b64.clear();
          do {
            b64.push_back(data.At(it++));
          } while (--cnt);
          b64.Encode(nullptr,0); // Force padding
          BegElt("b64"); Str(b64.c_str()); EndElt("b64");
        } while (len > 0);
      }
      break;
    }
  }

  if (type) {
    const int max = 64;
    do {
      int j, cnt = len > max ? max : len;
      char str[max+1]; // Needs to be flatten.
      str[max] = 0;
      for (j=0; j<cnt; ++j)
        str[j] = data.At(it++);
      BegElt(type); Str(str); EndElt(type);
      len -= cnt;
    } while (len > 0);
  }
  assert( it == data.Size() );
  return;
}
